import { Injectable, Inject, HttpStatus, } from "@nestjs/common";
import { ApiException } from "../../CoreModule/exception/api.exception";
import { ApiErrorCode } from "../../ShareModule/enums/api-error-code";
import { Repository } from "typeorm";
import { User } from "../../ShareModule/eneities/user.entity";
import { UserDto, editUserDto } from "./user.dto";

@Injectable()
export class UserService{
    constructor(
        @Inject('UserRepository') private readonly UserRepository:Repository<User>
    ){}

    async findAll():Promise<User[]> {
        return await this.UserRepository.find({
            select:['id','nickName','phone','userName','age','gender','email']
        });
    }

    async findOne(query:object):Promise<User> {
        return await this.UserRepository.findOne({
            where:query,
            select:['id','nickName','phone','userName','age','gender','email']
        });
    }

    async create(user:UserDto):Promise<User>{
        return await this.UserRepository.save(user);
    }

    async edit(user:editUserDto):Promise<User>{
        return await this.UserRepository.update({id:user.id},user);
    }

    async remove(id:number):Promise<User> {
        const user = await this.findOne({id});
        if(!user) throw new ApiException("无法删除不存在的用户",ApiErrorCode.PARAMS_LACK,HttpStatus.BAD_REQUEST);
        return await this.UserRepository.remove({id});
    }
}